package semantic_matching.entity_search.entity_tree;

import com.codahale.metrics.MetricRegistryListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import query_understanding.query_language.doc_entity_tree.QueryEdge;
import query_understanding.query_language.doc_entity_tree.QueryNode;
import semantic_matching.common.schema.MatchedEntites;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by julianzliu on 4/25/2017.
 */
public class QueryNodeSolver {
    static final Logger logger = LoggerFactory.getLogger(QueryNodeSolver.class);

    public QueryNodeSolver(){

    }

    public MatchedEntites solveNode(QueryNode.BaseNode node,Map<QueryNode.BaseNode, MatchedEntites> nodesEntities, Map<QueryEdge.BaseEdge, MatchedEntites> edgesEntities ) {
        logger.info("[solveNode] NodeType = {} , nodeSolvable = {}", node.nodeType, node.solveable);
        if (node.nodeType != QueryNode.NodeType.VARIABLE || node.solveable == false) {
            System.out.println("\n\n\n\n\n ERROR \n\n\n\n\n");
            return null;
        }
        /*
        Intersaction
         */
        Integer minSize = Integer.MAX_VALUE;
        QueryEdge.BaseEdge minEdge = null;
        for (QueryEdge.BaseEdge edge : node.outE) {
            if (edgesEntities.get(edge).entities.size() < minSize) {
                minEdge = edge;
                minSize = edgesEntities.get(edge).entities.size();
            }
        }
        Set<String> entites = new HashSet<>(edgesEntities.get(minEdge).entities);
        for (QueryEdge.BaseEdge edge : node.outE) {
            if (edge == minEdge) continue;
            Set<String> current = edgesEntities.get(edge).entities;
            for (String entity : entites) {
                if (!current.contains(entity)) {
                    entites.remove(entity);
                }
            }
        }

        MatchedEntites matchedEntites = new MatchedEntites();
        matchedEntites.entities = entites;

        nodesEntities.put(node, matchedEntites);

        node.solved = true;
        return matchedEntites;
    }

    /*
    http://blog.csdn.net/mhxy199288/article/details/37766679
     */
}
